package com.digital.smartgrow.common.util;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;

@Component
public class FileUtil {

    private static Logger logger = LoggerFactory.getLogger(FileUtil.class);

    /**
     * 创建文件目录
     *
     * @param path
     */
    public static void mkdir(String path) {
        path = checkPath(path);
        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdirs();
        }
    }

    /**
     * 检测路径格式
     *
     * @param str
     * @return
     */
    public static String checkPath(String str) {
        if (str.contains("\\")) {
            return str.replace("\\", "/");
        }
        return str;
    }

    /**
     * @param file
     */
    public static void removeAll(File file) {
        if (file.isDirectory()) {
            final File[] files = file.listFiles();
            final int len = files == null ? 0 : files.length;
            for (int i = 0; i < len; i++) {
                final File f = files[i];
                removeAll(f);
            }
            file.delete();
        } else {
            file.delete();
        }
    }

    /**
     * 复制文件
     *
     * @param src         原文件路径
     * @param destination 目的文件路径
     */
    public static void copy(String src, String destination) throws IOException {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        final int BUF_SIZE = 1024 * 3;
        try {
            bis = new BufferedInputStream(new FileInputStream(src));
            bos = new BufferedOutputStream(new FileOutputStream(destination));
            byte[] inbuf = new byte[BUF_SIZE];
            int n;

            while ((n = bis.read(inbuf)) != -1) {
                bos.write(inbuf, 0, n);
            }

            bis.close();
            bis = null;
            bos.close();
            bos = null;
        } catch (IOException ioe) {
            String msg = "Failed to copy [" + src + "] to [" + destination + "]";
            throw new IOException(msg);
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    // ignore
                }
            }
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    // ignore
                }
            }
        }
    }

    /**
     * 将文件流保存到文件
     */
    public static void save(final InputStream bis1, String destination) throws IOException {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        final int BUF_SIZE = 1024 * 3;
        try {
            bis = new BufferedInputStream(bis1);
            bos = new BufferedOutputStream(new FileOutputStream(destination));
            byte[] inbuf = new byte[BUF_SIZE];
            int n;

            while ((n = bis.read(inbuf)) != -1) {
                bos.write(inbuf, 0, n);
            }

            bis.close();
            bis = null;
            bos.close();
            bos = null;
        } catch (IOException ioe) {
            String msg = "Failed to save file to [" + destination + "]";
            throw new IOException(msg);
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    // ignore
                }
            }
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    // ignore
                }
            }
        }
    }

    /**
     * 获取文件的扩展名
     */
    public static String getExtName(String fileName) {
        final int pos = fileName == null ? -1 : fileName.lastIndexOf('.');
        return pos == -1 ? null : fileName.substring(pos + 1);
    }

    /**
     * 获取服务器路径
     *
     * @param url /api/upload/web/images/20180727/100622gfyTl.png
     * @return /usr/local/apache-tomcat-9.0.10/webapps/api/upload/web/images/20180727/100622gfyTl.png
     */
    public static String getServerPath(String url) {
        if (StringUtils.isBlank(url)) {
            return "";
        }
        String sysPath = FileUtil.class.getResource("/").getPath();
        int i = sysPath.indexOf("/api");
        if (i == -1) {
            return "";
        }
        return sysPath.substring(0, i) + url;
    }

    public static final InputStream fileNameToInputStream(String fileName) throws IOException {
        final File file = new File(fileName);
        final FileInputStream fi = new FileInputStream(file);
        final BufferedInputStream bis = new BufferedInputStream(fi);
        return bis;
    }

    /**
     * 保存上传文件 --->保存在应用目录下
     *
     * @param file 文件对象
     * @return
     */
    public static String saveFile(MultipartFile file) throws IOException {
        if (file == null) {
            return "";
        }
        String fileName = file.getOriginalFilename();
        int index = fileName.lastIndexOf(".");
        String time = LocalDateUtil.formatStrTime(LocalTime.now(), LocalDateUtil.hmsdtf);
        fileName = fileName.substring(0, index) + time + fileName.substring(index);

//        String basePath = new ClassPathResource("static").getFile().getPath();
        String basePath = checkPath(getRootPath());
        String savePath = checkPath(getSavePath());
        String filePath = basePath + savePath;
//        logger.info("文件上传路径为:{}", filePath);
        try {
            File targetFile = new File(filePath);
            if (!targetFile.exists()) {
                targetFile.mkdirs();
            }
            FileOutputStream out = new FileOutputStream(filePath + fileName);
            out.write(file.getBytes());
            out.flush();
            out.close();
            String returnPath = checkPath(savePath + fileName);
            return returnPath;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

//    /**
//     * 保存上传文件 --->保存在应用目录下
//     *
//     * @param data     文件对象
//     * @param typeName 目录 CommonUtil.getTypeName(2) 1-admin 2-web
//     * @param fileType 文件类型 0-图片 1-文件
//     * @return
//     */
//    public static String saveFile(byte[] data, String typeName, Integer fileType, String fileName) {
//        //String suffix = extName.startsWith(".") ? extName : ("." + extName);
//        //String fileName=DateUtil.formatDate(new Date(),DateUtil.HHmMsS)+suffix;
//        //使用MySQL动态配置路径
//        Map<String, String> versionMap = baseMapper.one("select innerNet,outerNet,linuxDir,windowDir from IpConfig where status=1");
//        String basePath = isLinux() ? versionMap.get("linuxDir") : versionMap.get("windowDir");
//        String savePath = checkPath(CommonUtil.getSavePath(typeName, fileType));
//        String filePath = basePath + "/" + savePath;
//        logger.info("文件上传路径为:{}", filePath);
//        try {
//            File targetFile = new File(filePath);
//            if (!targetFile.exists()) {
//                targetFile.mkdirs();
//            }
//            FileOutputStream out = new FileOutputStream(filePath + fileName);
//            out.write(data);
//            out.flush();
//            out.close();
//            //return checkPath(contextPath + File.separator + savePath + fileName);
//            String returnPath = checkPath(versionMap.get("outerNet") + "/" + savePath + fileName);
//            return returnPath;
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return "";
//    }

    /**
     * 保存上传文件
     *
     * @param files
     * @return
     */
    public static List<String> saveMultiFile(MultipartFile[] files) throws IOException {
        List<String> list = new ArrayList<String>();
        if (files != null && files.length > 0) {
            for (int i = 0; i < files.length; i++) {
                MultipartFile file = files[i];
                String path = saveFile(file);
                list.add(path);
            }
        }
        return list;
    }

    public static boolean isLinux() {
        return !System.getProperty("os.name").toLowerCase().contains("win");
    }

    /**
     * 获取文件保存路径
     *
     * @return
     */
    public static String getSavePath() {
        return File.separator + "upload" + File.separator + LocalDateUtil.formatStrTime(LocalDate.now(), LocalDateUtil.ymdDtf) + File.separator;
    }

    public static String getRootPath() {
        String path = "";
        ApplicationHome applicationHome = new ApplicationHome(FileUtil.class);
        File file = applicationHome.getSource();
        if (file != null) {
            path = file.getParentFile().getPath();
            File dir = new File(path + "/upload/");
            if (!dir.exists()) dir.mkdirs();
        }
        return path;
    }
}